package com.czy.service.impl;

import com.czy.mapper.ClazzMapper;
import com.czy.myexception.CustomException;
import com.czy.pojo.Clazz;
import com.czy.pojo.ClazzPage;
import com.czy.pojo.PageResult;
import com.czy.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult<Clazz> page(ClazzPage clazzPage) {
        //1. 设置分页参数
        PageHelper.startPage(clazzPage.getPage(), clazzPage.getPageSize());

        //2.执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzPage);

        //3.解析查询结果，并封装数据
        Page<Clazz> p = (Page<Clazz>) clazzList;

        return new PageResult<Clazz>(p.getTotal(),p.getResult());
    }

    @Override
    public void insert(Clazz clazz) {

        //补全基础属性，createTime和updateTime
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        //调用mapper新增班级
        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void updateById(Clazz clazz) {
        //补全基本属性，更新时间
        clazz.setUpdateTime(LocalDateTime.now());

        //调用mapper进行修改
        clazzMapper.updateById(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        //班级下关联的有学生，是不允许删除的
        Integer num = clazzMapper.getNum(id);
        if (num != null && num > 0){
            throw new CustomException(405,"班级下有学员，不能直接删除 ~ ");
        }

        clazzMapper.deleteById(id);
    }

    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }
}
